package cy.security.demo.security;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.social.security.SocialUser;
import org.springframework.social.security.SocialUserDetails;
import org.springframework.social.security.SocialUserDetailsService;
import org.springframework.stereotype.Component;

/**
 * @Author: ciyuan
 * @Date: 2019/5/18 13:34
 * TODO：自定义处理用户信息的获取逻辑实现
 */
@Component
public class MyUserDetailsServiceImpl implements UserDetailsService, SocialUserDetailsService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 表单登录时用，填写的时用户在表单登录时填写的用户名
     * @param username 表单登录时填写的用户名
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查找用户信息
        logger.info("表单登录用户名：" + username);

        // AuthorityUtils.commaSeparatedStringToAuthorityList("xxx","yyy") 用来把字符串转换成security所需要的权限对象集合
        // 根据查找到的用户信息判断用户是否被冻结
        return buildUser(username);
    }

    /**
     * 社交（第三方）登录时使用
     * @param userId SpringSocial根据appId和openId查询出来的userId
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public SocialUserDetails loadUserByUserId(String userId) throws UsernameNotFoundException {
        //根据用户id查找用户信息
        logger.info("社交登录用户Id" + userId);
        // AuthorityUtils.commaSeparatedStringToAuthorityList("xxx","yyy") 用来把字符串转换成security所需要的权限对象集合
        // 根据查找到的用户信息判断用户是否被冻结
        return buildUser(userId);
    }

    private SocialUserDetails buildUser(String userId) {
        String password = passwordEncoder.encode("123456");
        logger.info("数据库密码是："+password);
        return new SocialUser(userId,password,
                true,true,true,true,
                AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_ADMIN"));
    }
}
